package com.yijia.android.upload;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.protocol.HTTP;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;

public class FileUploadAsyncTask extends AsyncTask<File, Integer, String> {

	private Context context;
	private FileUploadListener fileUploadListener;
	private String baseUrl;
	private ProgressDialog pd;
	private long totalSize;

	public FileUploadAsyncTask(Context context,
			FileUploadListener mFileUploadListener, String baseUrl) {
		this.context = context;
		this.fileUploadListener = mFileUploadListener;
		this.baseUrl = baseUrl;
	}

	@Override
	protected void onPreExecute() {
		// pd = new ProgressDialog(context);
		// pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);// 水平进度条
		// // pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);// 转圈
		// pd.setMessage("上传中....");
		// pd.setCancelable(false);
		// pd.show();

		fileUploadListener.publishProgressShow();
	}

	@Override
	protected String doInBackground(File... params) {
		// 保存需上传文件信息
		MultipartEntityBuilder entitys = MultipartEntityBuilder.create();
		entitys.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
		entitys.setCharset(Charset.forName(HTTP.UTF_8));

		File file = params[0];
		entitys.addPart("file", new FileBody(file));

		HttpEntity httpEntity = entitys.build();
		totalSize = httpEntity.getContentLength();
		ProgressOutHttpEntity progressHttpEntity = new ProgressOutHttpEntity(
				httpEntity, new ProgressListener() {
					@Override
					public void transferred(long transferedBytes) {
						fileUploadListener.publishProgress(transferedBytes,
								totalSize);
						publishProgress((int) (100 * transferedBytes / totalSize));
					}
				});
		return uploadFile(baseUrl, progressHttpEntity);
	}

	@Override
	protected void onProgressUpdate(Integer... progress) {
		if (pd != null && pd.isShowing()) {
			pd.setProgress((int) (progress[0]));
		}
	}

	@Override
	protected void onPostExecute(String result) {
		if (pd != null && pd.isShowing()) {
			pd.dismiss();
		}
		fileUploadListener.publishProgressDismiss();
		System.out.println("读取服务器返回数据：result=" + result);
	}

	/**
	 * 上传文件到服务器
	 * 
	 * @param url
	 *            服务器地址
	 * @param entity
	 *            文件
	 * @return
	 */
	public String uploadFile(String url, ProgressOutHttpEntity entity) {
		HttpClient httpClient = new DefaultHttpClient();
		httpClient.getParams().setParameter(
				CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
		// 设置连接超时时间
		httpClient.getParams().setParameter(
				CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
		HttpPost httpPost = new HttpPost(url);
		httpPost.setEntity(entity);
		try {
			HttpResponse httpResponse = httpClient.execute(httpPost);
			if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				String result = handleEntity(httpResponse.getEntity(), "utf-8");
				return result;
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ConnectTimeoutException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (httpClient != null && httpClient.getConnectionManager() != null) {
				httpClient.getConnectionManager().shutdown();
			}
		}
		return "文件上传失败";
	}

	/**
	 * @Title: handleEntity
	 * @Description: TODO(服务器返回数据)
	 * @param @param entity
	 * @param @param charset
	 * @param @return
	 * @return String
	 * @throws
	 */
	public static String handleEntity(HttpEntity entity, String charset) {
		String result = "404";
		try {
			ByteArrayOutputStream outStream = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];

			long count = entity.getContentLength();// 内容长度
			long curCount = 0;
			int len = -1;
			InputStream is = entity.getContent();
			while ((len = is.read(buffer)) != -1) {
				outStream.write(buffer, 0, len);
				curCount += len;
				System.out.println("读取服务器返回数据：count=" + count + ";curCount="
						+ curCount);
			}

			byte[] data = outStream.toByteArray();
			outStream.close();
			is.close();

			result = new String(data, charset);
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

}
